package pers.wk.queues.dlx;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 普通消费者
 */
@Slf4j
public class NormalConsumer {

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();
            //4.声明正常交换机
            channel.exchangeDeclare(MQConfig.ExchangeName.DIRECT_EXCHANGE, MQConfig.ExchangeType.direct);
            //5.声明正常队列，设置队列参数，指定死信交换机
            Map<String, Object> argsMap = new HashMap<>();
            argsMap.put("x-dead-letter-exchange", MQConfig.ExchangeName.DLX_EXCHANGE);
            argsMap.put("x-dead-letter-routing-key", "error");
            channel.queueDeclare(MQConfig.QueueNames.EMAIL_QUEUE,
                    false, false, false, argsMap);

            //队列绑定交换机
            String routingKey = "email.info";
            channel.queueBind(MQConfig.QueueNames.EMAIL_QUEUE, MQConfig.ExchangeName.DIRECT_EXCHANGE, routingKey);
            System.out.println("普通消费者启动。。。");

            Channel channelTemp = channel;
            channelTemp.basicConsume(MQConfig.QueueNames.EMAIL_QUEUE, false, (consumerTag, message) -> {
                //@FunctionalInterface DeliverCallback
                Envelope envelope = message.getEnvelope();
                System.out.println(MessageFormat.format("普通消费者获取消息：【{1}】{0}【key:{2}】",
                        new String(message.getBody(), "UTF-8")
                        , message.getEnvelope().getDeliveryTag(), envelope.getRoutingKey()));
                log.info("get message, routingKey: {}, message: {}", envelope.getRoutingKey(), message);
                //channelTemp.basicAck(envelope.getDeliveryTag(), false);
                //requeue为true会重新入列
                //正常队列绑定了死信队列，拒绝消息，消息会投递到死信队列中
                channelTemp.basicReject(envelope.getDeliveryTag(), false);
            }, (consumerTag) -> {
                //@FunctionalInterface CancelCallback
            });

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MQConnectionUtils.close(connection, channel);
        }
    }
}
